package cn.xd.base.application.service.command.impl;

import cn.hutool.core.util.IdUtil;
import cn.xd.base.application.assembler.AdminOrgAssembler;
import cn.xd.base.application.service.command.AdminOrgAppService;
import cn.xd.base.basic.type.AdminOrgId;
import cn.xd.base.domain.bean.command.AddAdminOrgCommand;
import cn.xd.base.domain.bean.command.UpdateAdminOrgCommand;
import cn.xd.base.domain.bean.response.AdminOrgDTO;
import cn.xd.base.domain.entity.AdminOrg;
import cn.xd.base.domain.repository.AdminOrgRepository;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AdminOrgAppServiceImpl implements AdminOrgAppService {

    @Resource
    private AdminOrgRepository adminOrgRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AdminOrgDTO addAdminOrg(AddAdminOrgCommand command, Long userId) {
        command.setId(IdUtil.getSnowflakeNextId());
        AdminOrg add = AdminOrg.add(command, userId);
        adminOrgRepository.save(add);
        return AdminOrgAssembler.INSTANCE.toDTO(add);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AdminOrgDTO updateAdminOrg(UpdateAdminOrgCommand command, Long userId) {
        AdminOrg adminOrg = adminOrgRepository.find(AdminOrgId.of(command.getId())).isEmptyThrow("机构不存在");
        adminOrg.update(command, userId);
        adminOrgRepository.save(adminOrg);
        return AdminOrgAssembler.INSTANCE.toDTO(adminOrg);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAdminOrg(Long id) {
        AdminOrg adminOrg = adminOrgRepository.find(AdminOrgId.of(id)).isEmptyThrow("机构不存在");
        adminOrgRepository.remove(adminOrg);
    }
}
